package com.xxx.rpc.common.utils;

import java.lang.reflect.Field;

import org.springframework.context.ApplicationContext;
import org.springframework.util.StringValueResolver;

import com.xxx.rpc.common.xml.Dubbo;
import com.xxx.rpc.common.xml.tems.Application;
import com.xxx.rpc.common.xml.tems.Protocol;
import com.xxx.rpc.common.xml.tems.Registry;

public class WrapperDubboUtils {

	public static Dubbo wrapper(ApplicationContext applicationContext,StringValueResolver resolver) {
		Dubbo dubbo = applicationContext.getBean(Dubbo.class);
		if (dubbo != null) {
			warpDubbo(dubbo,resolver);
		}
		return dubbo;
	}
	
	public static void wrapper(Dubbo dubbo,StringValueResolver resolver) {
		if (dubbo != null) {
			warpDubbo(dubbo,resolver);
		}
	}
	
	
	private static void warpDubbo(Dubbo dubbo,StringValueResolver resolver) {
		System.out.println("warpDubbo start");
		Class<?> objClz = dubbo.getClass();

		Application application = dubbo.getApplication();
		String name = application.getName();
		
		application.setName(resolver.resolveStringValue(name));

		Registry registry = dubbo.getRegistry();
		String address = registry.getAddress();
		
		registry.setAddress(resolver.resolveStringValue(address));

		Protocol protocol = dubbo.getProtocol();
		String protocolName = protocol.getName();
		protocol.setName(resolver.resolveStringValue(protocolName));

		String portStr = protocol.getPortStr();
		protocol.setPort(Integer.parseInt(resolver.resolveStringValue(portStr)));
		for (Field field : objClz.getDeclaredFields()) {
			if (Application.class == field.getType()) {
				field.setAccessible(true);
				try {
					field.set(dubbo, application);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (Registry.class == field.getType()) {
				field.setAccessible(true);
				try {
					field.set(dubbo, registry);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (Protocol.class == field.getType()) {
				field.setAccessible(true);
				try {
					field.set(dubbo, protocol);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("warpDubbo end");
	}
	
}
